package org.hank.wanandroid.ui.widget

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.compose.foundation.layout.height
import androidx.compose.material.MaterialTheme
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewModelScope
import kotlinx.android.synthetic.main.fragment_article_recycler.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.hank.commom.base.BaseBindingFragment
import org.hank.commom.listener.ReloadListener
import org.hank.wanandroid.R
import org.hank.wanandroid.bean.ArticleBean
import org.hank.wanandroid.bean.LogoutEvent
import org.hank.wanandroid.constants.Constants
import org.hank.wanandroid.databinding.FragmentArticleRecyclerBinding
import org.hank.wanandroid.http.HttpConfig
import org.hank.wanandroid.listener.OnArticleRecyclerListener
import org.hank.wanandroid.ui.LoginActivity
import org.hank.wanandroid.ui.WebActivity
import org.hank.wanandroid.utils.AppManager
import org.hank.wanandroid.utils.ArticleHistoryUtil
import org.hank.wanandroid.utils.showSnackToast
import org.hank.wanandroid.viewmodel.ArticleViewModel

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2021/4/21 15:08
 *描述: 统一展示 列表文章 (搜索、历史记录、收藏等通用页面)
 */
class ArticleRecycleWidget(var articleRecyclerListener: OnArticleRecyclerListener? = null) :
    BaseBindingFragment<FragmentArticleRecyclerBinding>(R.layout.fragment_article_recycler),
    ReloadListener {

    private val articleViewModel by getViewModel(ArticleViewModel::class.java) {
        collectionRet.observe(it) {
            if (it) {
                this.collectChange(currentItem)
            }
        }
        unCollectionRet.observe(it) {
            if (it) {
                if (isCollect) {
                    this.unCollectChange(currentItem,true)
                    if (this.articleListData.value.isEmpty())
                        loadingTip_article_recycler.showEmpty()
                } else {
                    this.unCollectChange(currentItem,false)
                }
            }
        }
    }
    var isCollect = false
    var contentHeight = -1
    lateinit var currentItem: ArticleBean

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val onItemClick: (articleBean: ArticleBean) -> Unit = { item ->
            articleViewModel.viewModelScope.launch(Dispatchers.IO) {
                ArticleHistoryUtil.saveArticle(item)
            }
            var intent = Intent(context, WebActivity::class.java)
            var bundle = Bundle()
            var link =
                if (item.link.startsWith("/"))
                    HttpConfig.BASE_URL_MAP + item.link
                else
                    item.link
            bundle.putString(Constants.WEB_URL, link)
            bundle.putString(Constants.WEB_TITLE, item.title)
            intent.putExtras(bundle)
            startActivity(intent)
        }
        val onCollectClick: (articleBean: ArticleBean) -> Unit = { item ->
            if (!AppManager.isLogin()) {
                startActivity(Intent(activity, LoginActivity::class.java))
            } else {
                currentItem = item
                var delId =
                    if (isCollect) item.originId else item.id
                if (item.collect)
                    articleViewModel.unCollectArticle(delId)
                else
                    articleViewModel.collectArticle(delId)
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            contentHeight = activity!!.windowManager.currentWindowMetrics.bounds.height()
        } else {
            contentHeight = activity!!.windowManager.defaultDisplay.height
        }
        column_compose.setContent {
            MaterialTheme {
                lazyColumnContent(
                    modifier = Modifier.height(contentHeight.dp),
                    viewModel = articleViewModel,
                    OnItemClick = onItemClick,
                    OnCollectClick = onCollectClick
                )
            }
        }
        super.onViewCreated(view, savedInstanceState)
    }

    /**
     * 外部请求到数据
     */
    public fun validateData(data: MutableList<ArticleBean>?, isCollect: Boolean = false) {
        this.isCollect = isCollect
        loadingTip_article_recycler.dismiss()
        if (data.isNullOrEmpty()) {
            if (articleViewModel.articleListData.value.isEmpty()) {
                loadingTip_article_recycler.showEmpty()
            } else {
                showSnackToast("没有更多数据")
            }
        } else {
            if (isCollect) {
                for (item in data) {
                    item.collect = true
                }
            }
            articleViewModel.updateArticleList(data)
        }
    }

    /**
     * 外部通知本页面  数据刷新了
     */
    public fun notifyReload() {
        articleViewModel.reloadArticleList()
    }

    override fun reload() {
        articleRecyclerListener!!.onReload()
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: LogoutEvent?) {
        //登出 重置所有收藏状态
        articleViewModel.logoutFlow()
    }
}